<?php

namespace App\Http\Controllers\Admins\Organization;

use App\Http\Controllers\Admins\BaseAdminController;
use App\Models\Banner;
use App\Models\OperationalLogs;
use Carbon\Carbon;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class DepartmentController extends BaseAdminController
{
    public function index(Request  $request){
        $condition = $request->get('condition','depatment_name');
        if($request->isMethod('post')){
            # 要执行的代码
//            $roles = array('center','is_super_user');
            $query = Banner::query()->with(['admin','up'])->latest();
            $keywords = $request->get('keywords',null);
            if ($keywords && $condition == 'depatment_id') {
                $query->where($condition, 'like', '%' . $keywords . '%');
            }
//            $status = $request->get('status','all');
//            if($status != 'all'){
//                $query->where('status', $status);
//            }
            $pageSize = $request->get('limit',10);
            # 计算offset值
            $offset = $request->get('offset',0);
            # 总数
            $total = $query->count();
            $data = $query->limit($pageSize)->offset($offset)->get();
            $result = array();
            if($data){
                foreach($data as $val){
                    $up_department_name = '-';
                    $is_edit = 0;
                    if($val['parent_id'] != 0){
                        $up_department_name = $val['up']['department_name'];
                        $is_edit = 1;
                    }
                    $result[] = [
                        'id'=>$val['id'],
                        'department_name'=>$val['department_name'],
                        'up_department_name'=>$up_department_name,
                        'department_permissions'=>'-',#todo：待定
                        'is_edit'=>$is_edit,
                        'admin_name'=>$val['admin']['username'],
                        'crated_at'=>Carbon::parse($val['crated_at'])->toDateTimeString(),
                    ];
                }
            }
            return ret([
                'total'=>$total,
                'data'=>$result
            ]);
        }
        $admin_id = $this->admin_id;
        $subtitle = '部门管理';
        return view('v1.admin.organization.department.index',compact('subtitle','admin_id'));
    }

    /**
     * 获取全部数据
     *
     * @return array
     */
    private function getAllDepartData(): array
    {
        $query = Banner::query()->with(['admin','up'])->latest();
        $data = $query->get();
        $result = array();
        if($data){
            foreach($data as $val){
                $result[] = [
                    'id'=>$val['id'],
                    'name'=>$val['department_name'],
                ];
            }
        }
        return AdminRet([
            'data'=>$result
        ]);
    }
    /**
     * 创建部门
     *
     * @param Request $request
     * @return array|Application|Factory|View|RedirectResponse
     */
    public function create(Request $request)
    {
        $admin_id = $request->get('admin_id');
        $permissions = [
            [
                'id'=>1,
                'name'=>'管理'
            ],
            [
                'id'=>2,
                'name'=>'运营'
            ],
            [
                'id'=>3,
                'name'=>'招聘'
            ],
        ];
        if($request->isMethod('post')) {
            $table = 'department';
            # 表单验证
            $validator = AdminFormVerify($table, $request);
            if ($validator->fails()) {
                return $this->retError($validator,$request);
            }
            $department_name = $request->get('department_name');
            $create = [
                'department_name' => $department_name,
                'department_permissions' => '',
                'parent_id' => $request->get('parent_id', 0),
                'add_admin_id' => $admin_id,
            ];
            $logs = [
                'admin_id' => $admin_id,
                'operate_menu' => OperationalLogs::$operateItem['department_manage'],
                'operate_item' => $department_name,
                'operate_content' => '添加部门：' . $department_name,
            ];
            DB::beginTransaction();
            try {
                Banner::query()->create($create);
                #操作日志
                OperationalLogs::AddOperationalLogs($logs);
                DB::commit();
                return $this->retSuccess();
            } catch (\Exception $exception) {
                DB::rollback();
                return $this->retError($exception->getMessage(),$request);
//                return AdminRetError($exception->getMessage());
            }
        }
        $url = route('v1.admin.organization.department.index');
        $params = [
            'url'=>$url,
            'success'=>'success'
        ];
        $subtitle = '新增部门';
        $view = 'v1.admin.organization.department.add';
        $dataAll = Banner::allData();
        $compact = compact('subtitle','permissions','params','dataAll');
        return view($view,$compact);
    }

    /**
     * 编辑部门
     *
     * @param Request $request
     * @param $id
     * @return Application|Factory|View|RedirectResponse
     */
    public function update(Request $request,$id)
    {
        $model = Banner::query();
        if(!$id){
            $msg = '信息ID不能为空';
            return $this->retError($msg,$request);
        }
        $where = [
            'id'=>$id
        ];
        $data = $model->where($where)->count();
        if($data <=0){
            $msg = '数据不存在或已删除';
            return $this->retError($msg,$request);
        }
        $name = Banner::query()->where('id',$id)->value('department_name');
        if($request->isMethod('post')) {
            $department_name = $request->get('department_name');
            if ($department_name == $name) {
                return $this->retSuccess();
            }
            $admin_id = $request->get('admin_id');
            $table = 'department';
            $validator = AdminFormVerify($table, $request, 'update');
            if ($validator->fails()) {
                return $this->retError($validator,$request);
            }
            $model = Banner::query();
            $data_unique = $model->where($where)->count();
            if($data_unique>0){
                $msg = '该部门名称已存在！';
                return $this->retError($msg,$request);
            }
            $update = [
                'department_name' => $department_name,
                'department_permissions' => '',
                'add_admin_id' => $admin_id,
            ];
            $logs = [
                'admin_id' => $admin_id,
                'operate_menu' => OperationalLogs::$operateItem['department_manage'],
                'operate_item' => $name,
                'operate_content' => '修改部门名称为' . $department_name,
            ];
            DB::beginTransaction();
            try {
                Banner::query()->where('id', $id)->update($update);
                #操作日志
                OperationalLogs::AddOperationalLogs($logs);
                DB::commit();
                return $this->retSuccess();
            } catch (\Exception $exception) {
                DB::rollback();
                return $this->retError($exception->getMessage(), $request);
            }
        }
        $url = route('v1.admin.organization.department.index');
        $params = [
            'url'=>$url,
            'success'=>'success'
        ];
        $subtitle = '编辑部门';
        $view = 'v1.admin.organization.department.edit';
        $compact = compact('subtitle','params','name');
        return view($view,$compact);
    }

    /**
     * 删除部门
     *
     * @param Request $request
     * @param $id
     * @return array
     * @throws \Throwable
     */
    public function delete(Request $request,$id): array
    {
        $where = [
            'parent_id'=>$id,
        ];
        $data = Banner::query()->where($where)->count();
        if($data > 0){
            $msg = '该部门下包含其他部门，请删除后，再删除该部门';
            return AdminRetError($msg);
        }
        $data = Banner::query()->where($where);
        $logs = [
            'admin_id'=>$request->get('admin_id'),
            'operate_menu'=>OperationalLogs::$operateItem['department_manage'],
            'operate_item'=>$request->get('admin')['username'],
            'operate_content'=>OperationalLogs::$operate['department_delete'],
        ];
        return AdminDeleteData($data,$logs);
    }
}
